
package com.neo.tiny.business.queue.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.business.queue.entity.QueueTicketMachineRelationDO;
import com.neo.tiny.business.queue.mapper.QueueTicketMachineRelationMapper;
import com.neo.tiny.business.queue.service.QueueTicketMachineRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 队列与取号机
 * @Author: yqz
 * @CreateDate: 2022-10-27 22:39:51
 */
@Service
public class QueueTicketMachineRelationServiceImpl extends ServiceImpl<QueueTicketMachineRelationMapper, QueueTicketMachineRelationDO> implements QueueTicketMachineRelationService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bindQueueWithMachine(Long machineId, List<Long> queueIds) {
        // 先删除关系
        this.remove(new LambdaQueryWrapper<QueueTicketMachineRelationDO>()
                .eq(QueueTicketMachineRelationDO::getTicketMachineId, machineId));
        if (Objects.isNull(machineId) || CollUtil.isEmpty(queueIds)) {
            return Boolean.TRUE;
        }

        List<QueueTicketMachineRelationDO> queueMachineList = queueIds.stream().map(queueId -> {
            QueueTicketMachineRelationDO relationDO = new QueueTicketMachineRelationDO();
            relationDO.setTicketMachineId(machineId);
            relationDO.setQueueId(queueId);
            return relationDO;
        }).collect(Collectors.toList());
        return this.saveBatch(queueMachineList);
    }

    @Override
    public Set<Long> listQueueIdsByMachineId(Long machineId) {
        List<QueueTicketMachineRelationDO> list = this.list(new LambdaQueryWrapper<QueueTicketMachineRelationDO>()
                .eq(QueueTicketMachineRelationDO::getTicketMachineId, machineId));

        Set<Long> queueIds = list.stream().map(QueueTicketMachineRelationDO::getQueueId)
                .collect(Collectors.toSet());
        return queueIds;
    }
}
